#include "hc595.h"
#include <string.h>
#include "rtthread.h"

uint8_t hc595_byte = 0;
uint8_t HC595_DMA_Buff[HC595_PWM_MAX] = {0};

void HC595_DMA_Start(void)
{
    HAL_SPI_Transmit_DMA(HC595_SPI, HC595_DMA_Buff, HC595_PWM_MAX);
}

void HC595_setPWM(uint8_t channel, uint16_t Pwm)
{
    if(Pwm < HC595_PWM_MAX)
    {
        uint16_t i = 0;
        for(; i < Pwm; i++)
        {
            HC595_DMA_Buff[i] = HC595_DMA_Buff[i] | (0x01 << channel);
        }
        for(; i < HC595_PWM_MAX; i++)
        {
            HC595_DMA_Buff[i] = HC595_DMA_Buff[i] & (0xff ^ (0x01 << channel));
        }
    }
}

void HC595_WriteByte(uint8_t data)
{
    HAL_SPI_Transmit(HC595_SPI, &data, 1, 10);
}

void HC595_Write(uint8_t channel, uint8_t state)
{
    // 修改指定通道的状态
    if (state) {
        hc595_byte |= (1 << channel); // 将指定bit位置1
    } else {
        hc595_byte &= ~(1 << channel); // 将指定bit位置0
    }
    // 更新595芯片的输出状态
    HC595_WriteByte(hc595_byte);
}

void HC595_Toggle(uint8_t channel)
{
    // 翻转指定通道的状态
    hc595_byte ^= (1 << channel); // 将指定bit位翻转
    // 更新595芯片的输出状态
    HC595_WriteByte(hc595_byte);
}